package com.heima.kafka.simple;

import org.apache.kafka.clients.consumer.*;
import org.apache.kafka.common.TopicPartition;

import java.time.Duration;
import java.util.Collections;
import java.util.Map;
import java.util.Properties;

/**
 * 消费者快速入门
 * 消费者应该是一直处于监听状态，
 */
public class ConsumerStart {

    public static void main(String[] args) {
        //2.设置配置信息
        Properties properties=new Properties();
        //连接kafka地址信息
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,"192.168.200.104:9092");
        //对消息的key和value进行反序列化
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringDeserializer");
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringDeserializer");
        //必须加上组id的配置
        properties.put(ConsumerConfig.GROUP_ID_CONFIG,"group2");

        properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG,"false");//把自动提交偏移量改为手动提交
        //1.创建消费者对象
        KafkaConsumer<String,String> kafkaConsumer=new KafkaConsumer<String, String>(properties);

        /**
         * 3.订阅消息主题
         */
        kafkaConsumer.subscribe(Collections.singletonList("stream_get_topic"));


        while (true){
            //拉取消息
            ConsumerRecords<String, String> consumerRecords = kafkaConsumer.poll(Duration.ofMillis(10000));
            for (ConsumerRecord<String, String> consumerRecord : consumerRecords) {
                System.out.println("消息的key:"+consumerRecord.key()+",消息的value："+consumerRecord.value());
                //同步提交偏移量
                //kafkaConsumer.commitSync();
                //异步提交偏移量
               /* kafkaConsumer.commitAsync(new OffsetCommitCallback() {
                    @Override
                    public void onComplete(Map<TopicPartition, OffsetAndMetadata> offsets, Exception exception) {

                    }
                });*/
            }

        }

    }
}
